package com.example.hospitaltraining.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.hospitaltraining.common.PageUtils;
import com.example.hospitaltraining.common.R;
import com.example.hospitaltraining.config.AuthAccess;
import com.example.hospitaltraining.pojo.UserMsg;
import com.example.hospitaltraining.service.UserMsgService;
import com.example.hospitaltraining.utils.SM4DecryptionExample;
import com.example.hospitaltraining.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RequestMapping("/usermsg")
@RestController
public class UserMsgController {


    @Autowired
    private  UserMsgService userMsgService;






    /**
     * 分页查询
     * @param userMsg
     * @return
     */
    @AuthAccess
    @PostMapping("/login")
    private R login(@RequestBody UserMsg userMsg){
        String key  = "0123456789abcdeffedcba9876543210";
        System.out.println(userMsg.getId());
        if(userMsg.getId()!=null&&userMsg.getId().equals("1")){
            userMsg.setName(SM4DecryptionExample.decrypt(key,userMsg.getName()));
            userMsg.setIdNumber(SM4DecryptionExample.decrypt(key,userMsg.getIdNumber()));
        }

        LambdaQueryWrapper<UserMsg> qw = new LambdaQueryWrapper<>();
        qw.eq(UserMsg::getName,userMsg.getName());
        qw.eq(UserMsg::getIdNumber,userMsg.getIdNumber());
        UserMsg one = userMsgService.getOne(qw);
        if(one!=null){
            if(one.getId().equals("1")){
                if(Integer.parseInt(one.getAge())>=10){
                    return R.error("已锁定请联系管理员！");
                }
                one.setAge("0");
                userMsgService.updateById(one);
                one.setName(SM4DecryptionExample.encrypt(key,one.getName()));
                one.setIdNumber(SM4DecryptionExample.encrypt(key,one.getIdNumber()));
                return R.ok().put("data",one).put("token", TokenUtils.genToken(Long.valueOf(one.getId()),one.getIdNumber()));
            }
            return R.ok().put("data",one);
        }else {
            if(userMsg.getId().equals("1")){
                UserMsg byId = userMsgService.getById("1");
                if(Integer.parseInt(byId.getAge())>=10){
                    return R.error("已锁定请联系管理员！");
                }
                byId.setAge(String.valueOf(Integer.parseInt(byId.getAge())+1));
                userMsgService.updateById(byId);
                return R.error("密码错误！剩余次数:"+(10-Integer.parseInt(byId.getAge())));
            }
            return R.error("查无此人请再次提交申请！");
        }

    }


    /**
     * 分页查询
     * @param params
     * @return
     */
    @PostMapping("/list")
    private R list(@RequestParam Map<String, Object> params){
        PageUtils userPage = userMsgService.testpage(params);
        return R.ok().put("data",userPage);
    }

    @GetMapping("/getbyid/{id}")
    private R getById(@PathVariable Long id){
        UserMsg byId = userMsgService.getById(id);
        return R.ok().put("data",byId);
    }
    /**
     * 添加数据
     * @param userMsg
     * @return
     */
    @AuthAccess
    @PostMapping("/saveorupdata")
    private R save(@RequestBody UserMsg userMsg){
        LambdaQueryWrapper<UserMsg> qw = new LambdaQueryWrapper<>();
        qw.eq(UserMsg::getName,userMsg.getName());
        UserMsg one = userMsgService.getOne(qw);
        if (one!=null){
            if(one.getAuditStatus()==null){
                userMsg.setId(one.getId());
                userMsgService.updateById(userMsg);
                return R.ok().put("data","修改密码成功");
            }
            if(one.getAuditStatus().equals("已通过")){
                return R.ok().put("data","您已经通过审核请去查看录取结果！！");
            }
            userMsg.setAuditStatus("未审核");
            userMsg.setId(one.getId());
            userMsgService.updateById(userMsg);
            return R.ok().put("data","1");
        }else {
            userMsg.setAuditStatus("未审核");
            userMsgService.save(userMsg);
            return R.ok().put("data","提交成功！！");
        }
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    private R deleteIds(@RequestBody Long[] ids){
        userMsgService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 审核
     * @param
     * @return
     */
    @PostMapping("/audit")
    private R deleteIds(@RequestBody UserMsg userMsg){
        userMsgService.updateById(userMsg);
        return R.ok();
    }



    /**
     * 导出excel
     * @param
     * @return
     */
    @GetMapping("/importexcel")
    private void importExcel( HttpServletResponse response, HttpServletRequest request) {
        List<UserMsg> exportList = userMsgService.list();
        //查询数据源

        try {
            String fileName = "录入数据信息";

                // 非IE浏览器的处理:
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName + ".xlsx"));
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", -1);
            response.setCharacterEncoding("UTF-8");
            EasyExcel.write(response.getOutputStream(), UserMsg.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("导出列表")
                    .doWrite(exportList);
        } catch (Exception e) {
            System.err.println("导出失败");
        }
    }

}
